require('mysql')
const path = require('path')
const fs = require('fs')
const orm = require('orm')
const Promise = require('bluebird')
const { db_config } = require('../config/db')

// 初始化ORM
function InitOrmModel (app, callback) {
    app.use(orm.express(db_config, {
        define: function(db, models, next) {
            app.db = db
            global.db = db

            // 读取models路径下的所有模型文件
            const modelsPath = path.join(process.cwd(), '/models')
            
            fs.readdir(modelsPath, function (err, files) {
                const loadModelsFns = new Array()
                if (err) {
                    console.error('ORM模型加载出错: ',err)
                } else {
                    for(let i = 0; i < files.length; i++) {
                        const modelPath = modelsPath + '/' + files[i]
                        loadModelsFns[i] = db.loadAsync(modelPath)
                    }

                    Promise.all(loadModelsFns).then(() => {
                        console.log('ORM模型加载完成')
                        for (const modelName in db.models) {
                            models[modelName] = db.models[modelName]
                        }
                        app.models = models
                        callback(null)
                        next()
                    }).catch((error) => {
                        console.error('加载模块出错 error: ' + err);
                        callback(error);
                        next();
                    })
                }
            })
        }
    }))
}

module.exports.InitOrmModel = InitOrmModel
module.exports.getDataBase = function () {
    return global.db
}
